package com.daifeng.gulimall.carts.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.daifeng.common.utils.R;
import com.daifeng.gulimall.carts.Interceptor.CartInterceptor;
import com.daifeng.gulimall.carts.feign.ProductFeignService;
import com.daifeng.gulimall.carts.service.CartService;
import com.daifeng.gulimall.carts.vo.Skuvo;
import com.daifeng.gulimall.carts.vo.UserInfoTo;
import com.daifeng.gulimall.carts.vo.Cart;
import com.daifeng.gulimall.carts.vo.CartItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String CART_PREFIX = "gulimall:Cart:";

    @Resource
    ProductFeignService feignService;


    /**
     * 去redis中根据商品的skuid查询购物项  具体某一个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        CartItem item = JSON.parseObject((String) operations.get(skuId.toString()),CartItem.class);
        return item;
    }

    /**
     * 获取购物车信息
     * @return
     */
    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 判断用户是否登录
        if(userInfoTo.getUserId() != null){
            // 登录了就获取当前用户的购物车 并合并临时购物车中的数据
            // 1. 获取临时购物车数据
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String TempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(TempCartKey);
            if(cartItems != null && cartItems.size()>0){
                for (CartItem cartItem : cartItems) {
                    // 将临时购物车数据添加到用户购物车去
                    addCart(cartItem.getSkuid(),cartItem.getCount());
                }
                // 并清空临时购物车
                emptyCart(TempCartKey);
            }
            // 再获取用户购物车
            List<CartItem> carts = getCartItems(cartKey);
            cart.setItems(carts);
        }else {
            // 没有登录就获取临时购物车中的数据
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 清空购物车
     * @param tempCartKey
     */
    @Override
    public void emptyCart(String tempCartKey) {
        redisTemplate.delete(tempCartKey);
    }

    /**
     * 根据购物车的key获取该购物车的所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        //  获取全部购物项
        List<Object> values = operations.values();
        if(values != null && values.size()>0){
            List<CartItem> items = values.stream().map(obj -> {
                CartItem item = JSON.parseObject(obj.toString(), CartItem.class);
                return item;
            }).collect(Collectors.toList());
            return  items;
        }
        return  null;
    }

    /**
     * 添加商品到购物车 并返回添加的商品信息
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addCart(Long skuId, Integer num) {

        /**
         * 在redis中 key:用户标识(用户id或者user-key)   value:Hash（k：商品id，v：购物项详情）
         * Map<String k1,Map<String k2,CartItemInfo>>
         *     k1：标识每一个用户的购物车
         *     k2：购物项的商品id 在redis中 key:用户标识 value:Hash（k：商品id，v：购物项详情）
         */
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        // 根据商品id 获取具体信息  判断该商品是否已存在
        String s = (String) operations.get(skuId.toString());
        CartItem item = new CartItem();
        if(StringUtils.isEmpty(s)){
            // 如果没有获取到具体信息  则添加信息进redis  否则就数量加一
            R r = feignService.info(skuId);
            Skuvo skuvo = JSON.parseObject(JSON.toJSONString(r.get("skuInfo")) , new TypeReference<Skuvo>() {});
            List<String> skuSaleAttrValues = feignService.getSkuSaleAttrValues(skuId);
            item.setSkuid(skuvo.getSkuId());
            item.setCheck(true);
            item.setCount(num);
            item.setImage(skuvo.getSkuDefaultImg());
            item.setPrice(skuvo.getPrice());
            item.setTitle(skuvo.getSkuTitle());
            item.setSkuAttr(skuSaleAttrValues);
            operations.put(skuId.toString(),JSON.toJSONString(item));
        }else {
            // 存在就将该商品数量该变
            item = JSON.parseObject(s,CartItem.class);
            item.setCount(item.getCount()+num);
            operations.put(skuId.toString(),JSON.toJSONString(item));
        }
        return item;
    }

    /**
     * 获取我们要操作的购物车，临时购物车、用户购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {

        //得到用户信息 账号用户 、临时用户
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        //1、userInfoTo.getUserId()不为空表示账号用户，反之临时用户
        //    然后决定用临时购物车还是用户购物车
        //放入缓存的key
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 修改商品选中状态
     *
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Long check) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        // 根据id 获取要修改的购物项
        String s = (String) operations.get(skuId.toString());
        CartItem item = new CartItem();
        item = JSON.parseObject(s,CartItem.class);
        item.setCheck(check==1?true:false);
        operations.put(skuId.toString(),JSON.toJSONString(item));
    }

    /**
     * 改变商品数量
     *  @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String s = (String) operations.get(skuId.toString());
        CartItem item = new CartItem();
        item = JSON.parseObject(s,CartItem.class);
        item.setCount(num);
        operations.put(skuId.toString(),JSON.toJSONString(item));
    }

    /**
     * 获取所有购物车中选中的商品
     *
     * @return
     */
    @Override
    public List<CartItem> getCheckItems() {
        //得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cartItems.stream().filter( f->{
                // 留下购物车中选中的商品
                return f.getCheck();
            }).map(item->{
                //远程调用商品服务  保证价钱是最新价格
                R r = feignService.getinfoByid(item.getSkuid());
                String price = (String) r.get("data");
                item.setPrice(new BigDecimal(price));
                return item;
            }).collect(Collectors.toList());
            return  cartItems;
        }
        return null;
    }

    /**
     * 删除购物项
     *
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        operations.delete(skuId .toString());
    }

}
